// 后端路由
import { setDefaultRoute } from "@/utils/router-recursion";
//固定路由
import router, { DynamicRoutes, DynamicRoutesTwo } from "@/router/index";
import { RouteRecordRaw } from "vue-router";
import view from "@/components/view/view.vue";
import { Local } from "@/utils/storage";
import hook from "@/hooks";
import store from ".";

function typeOf(obj: any): any {
  const toString: any = Object.prototype.toString;
  const map: any = {
    "[object Boolean]": "boolean",
    "[object Number]": "number",
    "[object String]": "string",
    "[object Function]": "function",
    "[object Array]": "array",
    "[object Date]": "date",
    "[object RegExp]": "regExp",
    "[object Undefined]": "undefined",
    "[object Null]": "null",
    "[object Object]": "object",
  };
  return map[toString.call(obj)];
}
function clone(data: any): any {
  const t = typeOf(data);
  let o: any;

  if (t === "array") {
    o = [];
  } else if (t === "object") {
    o = {};
  } else {
    return data;
  }

  if (t === "array") {
    for (let i = 0; i < data.length; i++) {
      o.push(clone(data[i]));
    }
  } else if (t === "object") {
    for (const i in data) {
      o[i] = clone(data[i]);
    }
  }
  return o;
}
type RouterType = {
  name: string;
  path: string;
  meta: {
    hide: Boolean,
    icon: string,
    isMenu: Boolean,
    isSub: Boolean,
    name: string
  };
};
const actions = {
  /**
   * 获取动态路由，重新组装成菜单表
   * @param asyncRouter 后端路由
   */
  GenerateRoutes({ commit }: any, asyncRouter: RouteRecordRaw[] = []) {
    const routes: any = filterAsyncRouters(asyncRouter);
    if (routes) {
      const routerList: any = DynamicRoutes.map((item: any) => { return { ...item, children: routes } })
      const MainContainer = cloneDeep(routerList).find((v: any) => v.path === "");
      let children: RouteRecordRaw[] = [];
      children = MainContainer?.children;
      commit("SET_MENU", children);//设置顶部菜单
      MainContainer.children = children;
      setDefaultRoute([MainContainer]);
      MainContainer.children.push(
        {
          path: "/:pathMatch(.*)*",
          name: '404',
          component: () => import("@/pages/error/404/index.vue"),
          meta: {
            name: "404",
          },
        },
        {
          path: "/401",
          name: '401',
          component: () => import("@/pages/error/401/index.vue"),
          meta: {
            name: "401",
          },
        }
      );
      /*  初始路由 */
      const initialRoutes: any = router.options.routes;
      hook.menuHook.menuList = cloneDeep(MainContainer.children)
      router.addRoute(MainContainer)
      if (!store.getters.getCrumbList.length && MainContainer.children && MainContainer.children?.length) {
        const { meta, name } = MainContainer.children[0]
        const a = []
        a.push({ name, meta })
        //   //顶部面包屑
        commit("SET_CRUMB_LIST", a);
        // //目前左边导航选中的active
        commit("SET_CURRENT_MENU", name);
      }
      // /* 完整的路由表 */
      // // @ts-ignore //忽略提示
      // commit("SET_PERMISSION", [...initialRoutes, ...routerList]);
      commit("SET_PERMISSION", [MainContainer]);
    }
    // })
  },
  /**
   * 清空动态路由和菜单栏
   */
  async CLEAR_ALL_ROUTES({ commit }: any) {
    commit("SET_MENU", []);
    commit("SET_PERMISSION", []);
    commit("SET_CURRENT_MENU", "home");
    commit("SET_CURRENT_PATH", "/home");
  },
  FETCH_PERMISSION({ commit }: any, permissionList: RouteRecordRaw[] = []) {
    //处理需要动态的路由
    const routes: Array<any> = filterAsyncRouter(permissionList);
    console.log('routes:', routes);

    //不需要动态的路由（深拷贝）
    const MainContainer = clone(DynamicRoutesTwo).find((v: any) => v.path === "");
    let children: Array<any> = [];
    children = MainContainer.children;
    //将两种路由结合生成左边的导航栏
    children = children.concat(routes);
    commit("SET_MENU", children);
    MainContainer.children = children;
    setDefaultRoute([MainContainer]);
    /*  初始路由 */
    const initialRoutes = router.options.routes;
    router.addRoute('MainLayout', MainContainer);
    /* 完整的路由表 */
    // @ts-ignore //忽略提示
    commit("SET_PERMISSION", [...initialRoutes, ...DynamicRoutesTwo]);
  },
};
export const loadView = (views: String) => {
  const pathz: any = views;
  if (!pathz) {
    return () => view
  }
  const modules: any = import.meta.glob("../pages/**/**.vue")
  return modules[`../pages/${pathz}.vue`]
};


//递归处理后端数据
export function filterAsyncRouters(asyncRouterMap: RouteRecordRaw[] = []) {
  const routes: RouteRecordRaw[] = [];
  asyncRouterMap && asyncRouterMap?.forEach(item => {
    const tmpRoute: any = { ...item } as RouteRecordRaw;
    // item.visible
    if (tmpRoute.children) {
      // 对子菜单进行递归处理
      const childrenRoutes: any = filterAsyncRouters(tmpRoute.children);
      if (childrenRoutes.length) {
        routes.push({
          path: tmpRoute.path,
          name: tmpRoute.menuKey,
          component: loadView(tmpRoute.component),
          // component:()=>import(`../pages/${tmpRoute.component}`),
          // pathUrl: tmpRoute.component,
          children: childrenRoutes,
          meta: {
            nameEn: tmpRoute.nameEn,
            nameZh: tmpRoute.nameZh,
            nameAr: tmpRoute.nameAr,
            name: tmpRoute.nameZh,
            icon: tmpRoute.icon,
            isSub: tmpRoute.parentId !== 0 && tmpRoute.visible === 1,
            isMenu: tmpRoute.parentId === 0,
            isVisible: tmpRoute.visible === 1
          }
        });
      } else {
        routes.push({
          path: tmpRoute.path,
          name: tmpRoute.menuKey,
          component: loadView(tmpRoute.component),
          // component:()=>import(`../pages/${tmpRoute.component}`),
          // pathUrl: tmpRoute.component,
          meta: {
            nameEn: tmpRoute.nameEn,
            nameZh: tmpRoute.nameZh,
            nameAr: tmpRoute.nameAr,
            name: tmpRoute.nameZh,
            icon: tmpRoute.icon,
            isSub: tmpRoute.parentId !== 0 && tmpRoute.visible === 1,
            isMenu: tmpRoute.parentId === 0,
            isVisible: tmpRoute.visible === 1
          },
          // children: []
        });
      }
    }
    if (!tmpRoute.children && !tmpRoute.children.length) {
      delete item["children"]
      delete item["redirect"]
    }

  })
  return routes
}


//递归处理后端数据
function filterAsyncRouter(asyncRouterMap: Array<any>) {
  return asyncRouterMap.filter((route: any) => {
    if (route.children) {
      route.component = view;
    } else {
      route.component = loadView(route.component);
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children);
    } else {
      delete route["children"];
      delete route["redirect"];
    }
    return true;
  });

}

export default actions;
